package com.atguigu.juc.interview.lock;

import java.util.ArrayList;
import java.util.List;

/**
 * @author leimingchao
 * @create 2021-03-04 15:03
 */
public class ThreadEscapeDemo {

    private List<Integer> list = new ArrayList<>();

    public void test1() {
        List<Integer> localList = new ArrayList<>();
        localList.add(1);
        this.list = localList;

        try {
            // 睡1秒，让其他线程对类变量进行操作
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (Integer integer : localList) {
            // 如果线程安全，只会打印出1
            System.out.print(integer);
        }
    }

    public void test2() {
        this.list.add(2);
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadEscapeDemo escapeDemo = new ThreadEscapeDemo();
        Runnable test1 = escapeDemo::test1;
        Thread t1 = new Thread(escapeDemo::test1);
        Thread t2 = new Thread(escapeDemo::test2);

        t1.start();
        // 睡10毫秒，让t1先于t2运行
        Thread.sleep(10L);
        t2.start();
    }

}
